/**
 * WangSong 2009-10-2 从配置参数获取服务名称
 */
package cn.biplam.common.client;

import java.rmi.Naming;

import cn.biplam.common.interfaces.ServiceNameResolveServer;
import cn.biplam.common.paramters.index.ConfigParamIndex;
import cn.biplam.common.tools.RMITOOLS;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.KvMap;


/**
 * 名称解析服务客户端接口
 * @author 	WangSong
 * @create 	Mar 4, 2009 2:57:23 PM
 * @version 1.0
 */
public abstract class ServiceNameResolve {
	
	private static ServiceNameResolveServer mServiceNameResolveServer; //服务名称解析服务类实例
	private static KvMap<String,String> kvService;
	
	/**
	 * 根据指定服务名取服务信息
	 * @param   sServiceName 需要解析的服务名 	
	 * @throws ErrorMessage 
	 */
	public static String getUrlByName(String sServiceName) throws ErrorMessage{
		if(kvService==null){
			refresh();
		}
		if(sServiceName!=null){
			sServiceName = sServiceName.toUpperCase();
		}
		return kvService.getByKey(sServiceName);	
	}
	
	/**
	 * 从服务器端刷新配置信息
	 * @throws ErrorMessage 
	 */
	public static void refresh() throws ErrorMessage{
		ServiceNameResolveServer service = null;
		StringBuilder sb=new StringBuilder();
		try {
			//初始化服务器接口
			sb.append("rmi://");
			sb.append(Config.getProperte(ConfigParamIndex.SnrServer_Address));
			sb.append(':');
			sb.append(Config.getProperte(ConfigParamIndex.SnrServer_Port));
			sb.append('/');
			sb.append(Config.getProperte(ConfigParamIndex.SnrServer_Name));
			service = (ServiceNameResolveServer)Naming.lookup(sb.toString());
			kvService = service.getService();
		}catch(ErrorMessage e){
			throw e;
		}catch (Exception e) {
			throw new ErrorMessage(e,"Refresh service name failed!");
		}
	}
	
	/**
	 * 取服务器引用计数，重试指定次数
	 * @return 服务器引用计数器，失败返回-1
	 * @throws ErrorMessage 
	 */
	public int getCount() throws ErrorMessage {
		return RMITOOLS.getCount(mServiceNameResolveServer);
	}

	/**
	 * 同步上锁，直到获得锁
	 * @throws ErrorMessage 
	 */
	public void lock() throws ErrorMessage {
		RMITOOLS.lock(mServiceNameResolveServer);
	}

	/**
	 * 功能 尝试上锁，如果发生异常，重试系统指定次数
	 * @return 上锁成功时的服务器引用计数,-1代表等待超时
	 * @throws ErrorMessage 
	 * @throws NumberFormatException 
	 */
	public int trylock() throws NumberFormatException, ErrorMessage {
		return RMITOOLS.trylock(mServiceNameResolveServer);
	}

	/**
	 * 功能 尝试解锁，如果发生异常，重试系统指定次数
	 * @return	解锁成功时的服务器引用计数,-1代表等待超时
	 * @throws ErrorMessage 
	 * @throws NumberFormatException 
	 */
	public int unlock() throws NumberFormatException, ErrorMessage {
		return RMITOOLS.unlock(mServiceNameResolveServer);
	}
	
}
